﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.WeixinMP.Impls;
using Microhard.WeixinMP.Interfaces;
using Microhard.WeixinMP.Models;
using Micrhard.FMCG.Server.Interface;
using Microhard.Core;
using Micrhard.FMCG.Server.Msg;
using Microhard.Permission.Interface;

namespace Micrhard.FMCG.Server.Weixin
{
    public class GetMyClientInfo : BaseResponseImpl
    {
        public override Microhard.WeixinMP.Interfaces.WeixinCommand Command
        {
            get
            {
                WeixinCommand wc = new WeixinCommand();
                wc.Event = "CLICK";
                wc.EventKey = "myClient";
                return wc;
            }
        }

        protected override Microhard.WeixinMP.Models.WeixinBaseData<object> CreateFeatureResponse(Microhard.WeixinMP.Models.RequestServiceModel request, Microhard.WeixinMP.Models.WeixinBaseData<object> response)
        {
            response.MsgType = WeixinMsgType.Text;
            response.FuncFlag = WeixinMsgType.FuncFlag_False;
            WeixinTxt result = new WeixinTxt();

            //验证用户是否合法
            IWeiXinAccount iwa = IoC.Resolve<IWeiXinAccount>();
            string realUserName = string.Empty;
            bool illegal = iwa.ValidateByWeiXinUserName(response.ToUserName, out realUserName);
            if (illegal)
            {
                //生成消息
                ISubKA subKA = IoC.Resolve<ISubKA>();
                var kas = subKA.GetKAByWeixinOpenID(response.ToUserName);
                //拼装消息
                var gp = kas.GroupBy(g => g.KAName);
                StringBuilder msg = new StringBuilder();
                foreach (var g in gp)
                {
                    msg.AppendLine(string.Format(GetMyClientInfoMsg.ClientName, g.Key));
                    foreach (var k in g)
                    {
                        msg.AppendLine(string.Format(GetMyClientInfoMsg.ClientInfo, k.Name, k.Address, k.Contractor, k.Cellphone));
                    }
                }
                if (msg.Length == 0)
                {
                    result.Content = GetMyClientInfoMsg.NoneClientInfo;
                }
                else
                {
                    result.Content = msg.ToString();
                }
            }
            else
            {
                result.Content = GetMyClientInfoMsg.NoneUser;
            }
            response.Content = result;
            return response;
        }
    }
}
